package si.yun.utils.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import si.yun.config.properties.AliPayProperties;

import javax.annotation.PostConstruct;
import java.util.Map;


/**
 * 支付宝工具类
 * @author Administrator
 *
 */
@Component
public class AliPayUtil {
	
	@Autowired
	private AliPayProperties aliPayProperties ;

	private static AliPayProperties staticAliPayProperties;
	
	static AlipayClient alipayClient;
	
	/**
	 * 初始化
	 */
	@PostConstruct 
	public void init() {
		staticAliPayProperties = aliPayProperties;
		alipayClient = new DefaultAlipayClient(staticAliPayProperties.getAli_gatewayUrl(), staticAliPayProperties.getAli_app_id(), staticAliPayProperties.getAli_merchant_private_key(), "json", staticAliPayProperties.getAli_charset(), staticAliPayProperties.getAli_alipay_public_key(), staticAliPayProperties.getAli_sign_type());
	}
	/**
	 * alipay.trade.app.pay：原生手机APP支付测试（外部商户APP唤起快捷SDK创建订单并支付）
	 * @return String
	 */
	public static String alipayTradeAppPay(Map<String, Object> map){
        try {
			//（1）封装bizmodel信息
			AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
			//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
			String outTradeNo = (String) map.get("outTradeNo");
			String subject = (String) map.get("subject");
			String totalAmount = (String) map.get("totalAmount");
			String body = (String) map.get("body");
			model.setOutTradeNo(outTradeNo);
			model.setSubject(subject);
			model.setBody(body);
        	//（1）封装bizmodel信息
			model.setOutTradeNo(outTradeNo);
			model.setSubject(subject);
			model.setBody(body);
			model.setProductCode("QUICK_MSECURITY_PAY");
			model.setTotalAmount(totalAmount);
			model.setTimeoutExpress(staticAliPayProperties.getAli_timeout_express());
			//（2）设置请求参数
    		//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
			AlipayTradeAppPayRequest alipayRequest = new AlipayTradeAppPayRequest();
			alipayRequest.setNotifyUrl(staticAliPayProperties.getAli_notify_url());
			alipayRequest.setBizModel(model);                                                                                                                                                               
			//（3）请求
			//这里和普通的接口调用不同，使用的是sdkExecute
			String form = alipayClient.sdkExecute(alipayRequest).getBody();
			System.out.println("*********************\n返回结果为："+form);
			return form;
		} catch (AlipayApiException e) {
			e.printStackTrace();
			return null;
		}
    }
}
